var sw = 20,//一个方块的宽
    sh = 20,//一个方块的高
    tr = 30,//行数
    td = 30;//列数

    var snake = null,
        food = null,
        game = null;

//方块构造函数
function Square(x,y,classname){
    //0,0      0,0
    //20,0     1,0
    //40,0     2,0
    this.x = x*sw;
    this.y = y *sh;
    this.class = classname;
    // 指每一个小方块所对应的DOM元素
    this.viewContent = document.createElement("div");//方块对应的Dom元素
    this.viewContent.className = this.class;
    this.parent = document.getElementById("snakeWrap");//方块的父级
}
// new出来的实例都可以用
Square.prototype.create = function(){//创建方块DOM
    this.viewContent.style.position = 'absolute';
    this.viewContent.style.width = sw+'px';
    this.viewContent.style.height = sh + 'px';
    this.viewContent.style.left = this.x +'px';
    this.viewContent.style.top = this.y +'px';
   
    //添加到页面当中
    this.parent.appendChild(this.viewContent);
};
Square.prototype.remove = function(){
    // 删除元素
    this.parent.removeChild(this.viewContent);
}

//贪吃蛇的创建
function Snake(){
    this.head = null;//存贪吃蛇的头部
    this.tail = null;//存贪吃蛇的尾部
    this.pos = [];//存储贪吃蛇每个方块的位置

    this.directionNum = {//存储贪吃蛇走的方向，用对象来表示
      left:{
          x:-1,
          y:0,
          rotate:180 
      },
      right:{
          x:1,
          y:0,
          rotate:0
      },
      up:{
          x:0,
          y:-1,
          rotate:-90
      },
      down:{
          x:0,
          y:1,
          rotate:90
      }

    }
    
}
//初始化贪吃蛇
Snake.prototype.init = function(){
  //创建贪吃蛇的头部
  var snakeHead = new Square(2,0,'snakeHead');
//   创建了贪吃蛇头部
  snakeHead.create();
  this.head = snakeHead;//存储贪吃蛇的头部信息
  
  this.pos.push([2,0]);//把贪吃蛇的头部存起来

  //创建贪吃蛇的身体1
  var snakeBody1 = new Square(1,0,'snakeBody');
  snakeBody1.create();
  this.pos.push([1,0]);//存储贪吃蛇的身体坐标

  //创建贪吃蛇的身体2
  var snakeBody2 = new Square(0,0,'snakeBody');
  snakeBody2.create();
  this.tail = snakeBody2;//把贪吃蛇的尾部存起来
  this.pos.push([0,0]);//存储贪吃蛇的身体坐标

  //变为链表的关系
  snakeHead.last = null;
  snakeHead.next = snakeBody1;

  snakeBody1.last = snakeHead;
  snakeBody1.next = snakeBody2;

  snakeBody2.last = snakeBody1;
  snakeBody2.next = null;
  //给贪吃蛇添加一条默认的属性用来表示贪吃蛇走的方向
  this.direction = this.directionNum.right;//，默认情况下让贪吃蛇往右走
}

//这个方法用来获取贪吃蛇头部的下一个位置对于的元素，要根据元素做下不同的事情
Snake.prototype.getNextPos = function(){
    var nextPos = [
        this.head.x/sw +  this.direction.x,
        this.head.y/sh +  this.direction.y
    ]
    //下个点是自己,代表撞到自己游戏结束
    var selfCollied = false;//是否撞到自己
    this.pos.forEach(function(value){
      if(value[0] == nextPos[0] && value[1] == nextPos[1]){
        //   如果数组中的两个数据都相等，就说明下一个点在贪吃蛇的身上，代表撞到自己
          selfCollied = true;
      }
    });
    if(selfCollied){
        console.log('撞到自己了');
        this.strategies.die.call(this);
        return;
    }

    //下个点 代表撞到围墙游戏结束
    if(nextPos[0]<0 || nextPos[1] < 0 || nextPos[0]>td-1 ||nextPos[1]>tr-1){
       console.log('撞到围墙了');
       this.strategies.die.call(this);
       return;
    }
    //下个点是食物，吃
     // this.strategies.eat();
     if(food && food.pos[0]==nextPos[0] && food.pos[1]==nextPos[1]){
         console.log("撞到食物了");
        this.strategies.eat.call(this);
        return;
     }

    //下个点什么都不是 走
    this.strategies.move.call(this);
};

 //处理
 Snake.prototype.strategies = {
     move:function(format){
       //创建一个新的身体
       var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody');
        //更新链表
       newBody.next = this.head.next;
       newBody.next.last = newBody;
       newBody.last = null;
       this.head.remove();//把老的贪吃蛇的头部位置删除
       newBody.create();

       //创建一个新的贪吃蛇的头
        var newHead = new Square( this.head.x/sw +  this.direction.x, this.head.y/sh +  this.direction.y,'snakeHead');
        newHead.next = newBody;
        newHead.last = null;
        newBody.last = newHead;
        newHead.viewContent.style.transform = 'rotate('+this.direction.rotate+'deg)'
        newHead.create();
        //更新坐标
        this.pos.splice(0,0,[this.head.x/sw +  this.direction.x, this.head.y/sh +  this.direction.y]);
        this.head = newHead;//还要把this.head的信息更新一下
        
        if(!format){//如果formmat的值为false，表示需要删除
            this.tail.remove();
            this.tail=this.tail.last;

            this.pos.pop();
        }

     },
     eat:function(){
       this.strategies.move.call(this,true);
       createFood();
       game.score++;
     },
     die:function(){
    //  console.log('die');
     game.over();
     }
}
snake = new Snake();
// snake.init();
// snake.getNextPos();

//创建食物
function createFood(){
    // 食物的随机坐标
    var x = null;
    var y = null;

    var include = true; //循环跳出的条件
    while(include){
      x = Math.round(Math.random()*(td-1));
      y = Math.round(Math.random()*(tr-1));
      
      snake.pos.forEach(function(value){
        if(x != value[0] && y !=value[1]){
            // 这个条件成立
            include = false;
        }
      });
     
    }
    //生成食物
    food = new Square(x,y,'food');
    food.pos = [x,y];//存储生成食物的坐标
    var foodDom = document.querySelector(".food");
    if(foodDom){
        foodDom.style.left = x *sw+'px';
        foodDom.style.top = y *sh+'px';
    }else{
        food.create(); 
    }
    
}


//创建游戏
function Game(){
    this.timer = null;
    this.score = 0;
}
Game.prototype.init = function(){
    snake.init();
    createFood();

    document.onkeydown=function(ev){
        // 键盘事件
		if(ev.which==37 && snake.direction!=snake.directionNum.right){	//用户按下左键的时候，这条蛇不能是正下往右走
			snake.direction=snake.directionNum.left;
		}else if(ev.which==38 && snake.direction!=snake.directionNum.down){
			snake.direction=snake.directionNum.up;
		}else if(ev.which==39 && snake.direction!=snake.directionNum.left){
			snake.direction=snake.directionNum.right;
		}else if(ev.which==40 && snake.direction!=snake.directionNum.up){
			snake.direction=snake.directionNum.down;
		}
	}

	this.start();
}
Game.prototype.start = function(){//开始游戏
  this.timer = setInterval(function(){
    snake.getNextPos();
  },200);
}
Game.prototype.pause = function(){
    clearInterval(this.timer);
}
Game.prototype.over = function(){
    clearInterval(this.timer);
    alert('你的得分为:'+this.score)

    // 游戏回到最初的状态
    var snakeWrap = document.getElementById('snakeWrap');
    snakeWrap.innerHTML = "";
    snake = new Snake();
    game = new Game();

    var stratBtnWrap = document.querySelector(".stratBtn");
    stratBtnWrap.style.display = 'block';
}
//开启游戏
game = new Game();

var stratBtn = document.querySelector(".stratBtn button");
stratBtn.onclick=function(){
	stratBtn.parentNode.style.display='none';
	game.init();
};


//暂停游戏
var snakeWrap = document.getElementById('snakeWrap');
var pauseBtn = document.querySelector(".pauseBtn button")
snakeWrap.onclick = function(){
  game.pause();
  pauseBtn.parentNode.style.display = "block";
}

pauseBtn.onclick = function(){
    game.start();
    pauseBtn.parentNode.style.display = "none";
}

